package com.monitoramento.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.monitoramento.HibernateUtil;
import com.monitoramento.entity.Categoria;

public class CategoriaDaoImpl implements CategoriaDao{
	
	public void save(Categoria categoria){
		 Session session = HibernateUtil.getSessionFactory().openSession();
	        Transaction t = session.beginTransaction();
	        session.save(categoria);
	        t.commit();
	        session.close();
	}
	
	public void delete(Categoria categoria){
		Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.delete(categoria);
        t.commit();
        session.close();
	}
	
	 public void update(Categoria categoria) {
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        Transaction t = session.beginTransaction();
	        session.update(categoria);
	        t.commit();
	    }
	 
	 public List<Categoria> findAll() {
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        Transaction t = session.beginTransaction();
	        List<Categoria> lista = session.createQuery("from Categoria").list();
	        t.commit();
	        session.close();
	        return lista;
	    }
	 
	 public Categoria findByPK(long pk) {
	    	
	    	Session session = HibernateUtil.getSessionFactory().openSession();
	        Transaction t = session.beginTransaction();
	        Query query = session.createQuery("from Categoria p where p.id = :pk");
	        query.setParameter("pk", pk);
	        Categoria categoria =  (Categoria) query.uniqueResult();
	        t.commit();        
	        session.close();
	        return categoria;
	    }


}
